package com.lsh.util;

import java.security.MessageDigest;

public class MD5Util {

    private static char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

    /**
     * MD5加密
     * @param origin 字符
     * @param charsetName 编码
     * @return
     */
    public static String Md5Encode(String origin, String charsetName){
        try {
            byte[] b = origin.getBytes(charsetName);
            MessageDigest mdt = MessageDigest.getInstance("MD5"); //获得MD5摘要算法的MessageDigest对象
            mdt.update(b); //使用指定字节更新摘要
            byte[] md = mdt.digest(); //获得密文
            //把密文转成十六进制字符串形式
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for(int i=0;i<j;i++){
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0>>>4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
